package net.toocruel.iqismart.web.controller;

import net.toocruel.iqismart.entity.rbac.User;
import net.toocruel.iqismart.entity.validate.group.RegisterGroup;
import net.toocruel.iqismart.service.UserService;
import net.toocruel.iqismart.web.controller.base.AbstractBaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("account")
public class RegisterController extends AbstractBaseController {
    @Autowired
    private UserService userService;



    @GetMapping("register")
    public String register(User user,HttpServletRequest request){

        Object errs = request.getAttribute("errs");
        ModelAndView modelAndView = new ModelAndView();
        return getTemplate("/register");
    }

    @PostMapping("register")
    public String doRegister(@Validated(RegisterGroup.class) User user, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response){

        if(!bindingResult.hasErrors()){
            try {
                String username = user.getUsername();
                String password = user.getPassword();
//                String email = user.getEmail();
//                String mobile = user.getMobile();
                userService.register(user);
                login(username,password);
                return  "redirect:/";
            }catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }



        return getTemplate("register");
    }

    @Override
    protected String getModule() {
        return "account";
    }
}
